<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Facades\Storage;

trait HasImages
{
    /**
     * 获取图片关联
     */
    public function images(): MorphMany
    {
        return $this->morphMany(\App\Models\ProductImage::class, 'imageable');
    }

    /**
     * 获取主图片
     */
    public function mainImage()
    {
        return $this->images()->where('is_main', true)->first();
    }

    /**
     * 获取主图片URL
     */
    public function getMainImageUrlAttribute(): ?string
    {
        $mainImage = $this->mainImage();
        return $mainImage ? Storage::url($mainImage->path) : null;
    }

    /**
     * 获取所有图片URL
     */
    public function getImageUrlsAttribute(): array
    {
        return $this->images()->orderBy('sort_order')->get()->map(function ($image) {
            return [
                'id' => $image->id,
                'url' => Storage::url($image->path),
                'alt' => $image->alt,
                'is_main' => $image->is_main,
                'sort_order' => $image->sort_order,
            ];
        })->toArray();
    }

    /**
     * 添加图片
     */
    public function addImage(string $path, string $alt = null, bool $isMain = false, int $sortOrder = 0): \App\Models\ProductImage
    {
        // 如果设置为主图片，先取消其他主图片
        if ($isMain) {
            $this->images()->update(['is_main' => false]);
        }

        return $this->images()->create([
            'path' => $path,
            'alt' => $alt,
            'is_main' => $isMain,
            'sort_order' => $sortOrder,
        ]);
    }

    /**
     * 设置主图片
     */
    public function setMainImage(int $imageId): bool
    {
        // 先取消所有主图片
        $this->images()->update(['is_main' => false]);

        // 设置新的主图片
        return $this->images()->where('id', $imageId)->update(['is_main' => true]) > 0;
    }

    /**
     * 删除图片
     */
    public function removeImage(int $imageId): bool
    {
        $image = $this->images()->find($imageId);
        
        if (!$image) {
            return false;
        }

        // 删除文件
        if (Storage::exists($image->path)) {
            Storage::delete($image->path);
        }

        // 删除记录
        $image->delete();

        return true;
    }

    /**
     * 删除所有图片
     */
    public function removeAllImages(): int
    {
        $count = 0;
        
        foreach ($this->images as $image) {
            if ($this->removeImage($image->id)) {
                $count++;
            }
        }

        return $count;
    }

    /**
     * 更新图片排序
     */
    public function updateImageOrder(array $imageOrders): bool
    {
        foreach ($imageOrders as $imageId => $sortOrder) {
            $this->images()->where('id', $imageId)->update(['sort_order' => $sortOrder]);
        }

        return true;
    }

    /**
     * 获取图片数量
     */
    public function getImageCountAttribute(): int
    {
        return $this->images()->count();
    }

    /**
     * 检查是否有图片
     */
    public function hasImages(): bool
    {
        return $this->image_count > 0;
    }

    /**
     * 检查是否有主图片
     */
    public function hasMainImage(): bool
    {
        return $this->images()->where('is_main', true)->exists();
    }

    /**
     * 获取图片作用域
     */
    public function scopeWithImages($query)
    {
        return $query->with('images');
    }

    public function scopeWithMainImage($query)
    {
        return $query->with(['images' => function ($query) {
            $query->where('is_main', true);
        }]);
    }

    public function scopeHasImages($query)
    {
        return $query->whereHas('images');
    }

    public function scopeHasMainImage($query)
    {
        return $query->whereHas('images', function ($query) {
            $query->where('is_main', true);
        });
    }

    /**
     * 获取图片信息
     */
    public function getImageInfo(int $imageId): ?array
    {
        $image = $this->images()->find($imageId);
        
        if (!$image) {
            return null;
        }

        return [
            'id' => $image->id,
            'path' => $image->path,
            'url' => Storage::url($image->path),
            'alt' => $image->alt,
            'is_main' => $image->is_main,
            'sort_order' => $image->sort_order,
            'created_at' => $image->created_at,
            'updated_at' => $image->updated_at,
        ];
    }

    /**
     * 批量添加图片
     */
    public function addImages(array $imageData): array
    {
        $addedImages = [];
        
        foreach ($imageData as $data) {
            $image = $this->addImage(
                $data['path'],
                $data['alt'] ?? null,
                $data['is_main'] ?? false,
                $data['sort_order'] ?? 0
            );
            $addedImages[] = $image;
        }

        return $addedImages;
    }

    /**
     * 复制图片
     */
    public function copyImagesFrom($sourceModel): int
    {
        $count = 0;
        
        foreach ($sourceModel->images as $image) {
            $this->addImage(
                $image->path,
                $image->alt,
                $image->is_main,
                $image->sort_order
            );
            $count++;
        }

        return $count;
    }

    /**
     * 获取图片统计
     */
    public function getImageStats(): array
    {
        $images = $this->images;
        
        return [
            'total' => $images->count(),
            'main' => $images->where('is_main', true)->count(),
            'regular' => $images->where('is_main', false)->count(),
            'with_alt' => $images->whereNotNull('alt')->count(),
            'without_alt' => $images->whereNull('alt')->count(),
        ];
    }
}
